const mongoose = require('mongoose');

const shopApprovalHistorySchema = new mongoose.Schema({
  // 商店ID
  shop: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Shop',
    required: true
  },
  
  // 商店名称（冗余存储，避免商店删除后历史记录丢失）
  shopName: {
    type: String,
    required: true
  },
  
  // 操作类型
  action: {
    type: String,
    enum: ['approved', 'rejected', 'suspended', 'resumed', 'created'],
    required: true
  },
  
  // 操作原因/备注
  reason: {
    type: String,
    default: ''
  },
  
  // 操作人
  operator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Admin',
    required: true
  },
  
  // 操作人姓名（冗余存储）
  operatorName: {
    type: String,
    required: true
  },
  
  // 操作前状态
  previousStatus: {
    type: String,
    required: true
  },
  
  // 操作后状态
  newStatus: {
    type: String,
    required: true
  },
  
  // 操作时间
  createdAt: {
    type: Date,
    default: Date.now
  },
  
  // 额外的元数据
  metadata: {
    type: mongoose.Schema.Types.Mixed,
    default: {}
  }
}, {
  timestamps: true,
  collection: 'shop_approval_history'
});

// 索引
shopApprovalHistorySchema.index({ shop: 1, createdAt: -1 });
shopApprovalHistorySchema.index({ action: 1, createdAt: -1 });
shopApprovalHistorySchema.index({ operator: 1, createdAt: -1 });
shopApprovalHistorySchema.index({ createdAt: -1 });

// 静态方法：记录审核历史
shopApprovalHistorySchema.statics.recordApproval = async function(data) {
  const {
    shopId,
    shopName,
    action,
    reason,
    operatorId,
    operatorName,
    previousStatus,
    newStatus,
    metadata = {}
  } = data;

  try {
    const record = new this({
      shop: shopId,
      shopName,
      action,
      reason,
      operator: operatorId,
      operatorName,
      previousStatus,
      newStatus,
      metadata
    });

    await record.save();
    return record;
  } catch (error) {
    console.error('记录审核历史失败:', error);
    throw error;
  }
};

// 静态方法：获取商店的审核历史
shopApprovalHistorySchema.statics.getShopHistory = async function(shopId, options = {}) {
  const {
    page = 1,
    limit = 10,
    action,
    startDate,
    endDate
  } = options;

  const query = { shop: shopId };

  // 按操作类型筛选
  if (action) {
    query.action = action;
  }

  // 按时间范围筛选
  if (startDate || endDate) {
    query.createdAt = {};
    if (startDate) {
      query.createdAt.$gte = new Date(startDate);
    }
    if (endDate) {
      query.createdAt.$lte = new Date(endDate);
    }
  }

  const skip = (page - 1) * limit;
  const total = await this.countDocuments(query);

  const records = await this.find(query)
    .populate('shop', 'name logo')
    .populate('operator', 'name email')
    .sort({ createdAt: -1 })
    .skip(skip)
    .limit(limit);

  return {
    data: records,
    pagination: {
      current: page,
      pageSize: limit,
      total,
      pages: Math.ceil(total / limit)
    },
    total
  };
};

// 静态方法：获取全部审核历史
shopApprovalHistorySchema.statics.getAllHistory = async function(options = {}) {
  const {
    page = 1,
    limit = 10,
    keyword,
    action,
    startDate,
    endDate,
    operatorId
  } = options;

  const query = {};

  // 按关键词搜索商店名称
  if (keyword) {
    query.shopName = { $regex: keyword, $options: 'i' };
  }

  // 按操作类型筛选
  if (action) {
    query.action = action;
  }

  // 按操作人筛选
  if (operatorId) {
    query.operator = operatorId;
  }

  // 按时间范围筛选
  if (startDate || endDate) {
    query.createdAt = {};
    if (startDate) {
      query.createdAt.$gte = new Date(startDate);
    }
    if (endDate) {
      query.createdAt.$lte = new Date(endDate);
    }
  }

  const skip = (page - 1) * limit;
  const total = await this.countDocuments(query);

  const records = await this.find(query)
    .populate('shop', 'name logo')
    .populate('operator', 'name email')
    .sort({ createdAt: -1 })
    .skip(skip)
    .limit(limit);

  return {
    data: records,
    pagination: {
      current: page,
      pageSize: limit,
      total,
      pages: Math.ceil(total / limit)
    },
    total
  };
};

// 静态方法：获取审核统计
shopApprovalHistorySchema.statics.getApprovalStats = async function(options = {}) {
  const {
    startDate,
    endDate,
    operatorId
  } = options;

  const matchQuery = {};

  // 按时间范围筛选
  if (startDate || endDate) {
    matchQuery.createdAt = {};
    if (startDate) {
      matchQuery.createdAt.$gte = new Date(startDate);
    }
    if (endDate) {
      matchQuery.createdAt.$lte = new Date(endDate);
    }
  }

  // 按操作人筛选
  if (operatorId) {
    matchQuery.operator = mongoose.Types.ObjectId(operatorId);
  }

  const stats = await this.aggregate([
    { $match: matchQuery },
    {
      $group: {
        _id: '$action',
        count: { $sum: 1 }
      }
    }
  ]);

  // 转换为对象格式
  const result = {
    approved: 0,
    rejected: 0,
    suspended: 0,
    resumed: 0,
    created: 0
  };

  stats.forEach(stat => {
    result[stat._id] = stat.count;
  });

  return result;
};

module.exports = mongoose.model('ShopApprovalHistory', shopApprovalHistorySchema);
